home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 8684 / FAQ.002
Encoding:
Text File  |  1996-08-05  |  39.7 KB  |  972 lines

  1. Path: news1.h1.usa.pipeline.com!psinntp!psinntp!howland.reston.ans.net!newsfeed.internetmci.com!news.kei.com!newsstand.cit.cornell.edu!ub!library.erc.clarkson.edu!sun.soe.clarkson.edu!cline
  2. From: cline@sun.soe.clarkson.edu (Marshall Cline)
  3. Newsgroups: comp.lang.c++
  4. Subject: C++ FAQ: posting #2/4
  5. Followup-To: comp.lang.c++
  6. Date: 1 Feb 1996 03:20:20 GMT
  7. Organization: Paradigm Shift, Inc (technology consulting)
  8. Lines: 955
  9. Sender: cline@sun.soe.clarkson.edu
  10. Distribution: world
  11. Expires: +1 month
  12. Message-ID: <4epbhk$ghr@library.erc.clarkson.edu>
  13. Reply-To: cline@parashift.com (Marshall Cline)
  14. NNTP-Posting-Host: sun.soe.clarkson.edu
  15. Summary: Please read this before posting to comp.lang.c++
  16.  
  17. comp.lang.c++ Frequently Asked Questions list (with answers, fortunately).
  18. Copyright (C) 1991-96 Marshall P. Cline, Ph.D.
  19. Posting 2 of 4.
  20. Posting #1 explains copying permissions, (no)warranty, table-of-contents, etc
  21.  
  22. ==============================================================================
  23. SECTION 9: Freestore management
  24. ==============================================================================
  25.  
  26. Q33: Does "delete p" delete the pointer "p", or the pointed-to-data, "*p"?
  27.  
  28. The pointed-to-data.
  29.  
  30. "delete" really means "delete the thing pointed to by."  The same abuse of
  31. English occurs when "free"ing the memory pointed to by a ptr in C ("free(p)"
  32. really means "free_the_stuff_pointed_to_by(p)").
  33.  
  34. ==============================================================================
  35.  
  36. Q34: Can I "free()" pointers allocated with "new"?  Can I "delete" pointers
  37.    alloc'd with "malloc()"?
  38.  
  39. No.
  40.  
  41. It is perfectly legal, moral, and wholesome to use malloc/free and new/delete
  42. in the same program, but it is illegal, immoral, and despicable to free a
  43. pointer allocated via new, or to delete a pointer allocated via malloc.
  44.  
  45. ==============================================================================
  46.  
  47. Q35: Why should I use "new" instead of trustworthy old malloc()?
  48.  
  49. Constructors/destructors, type safety, overridability.
  50.  
  51. Constructors/destructors: unlike "malloc(sizeof(Fred))", "new Fred()" calls
  52. Fred's constructor.  Similarly, "delete p" calls "*p"'s destructor.
  53.  
  54. Type safety: malloc() returns a "void*" which isn't type safe.  "new Fred()"
  55. returns a ptr of the right type (a "Fred*").
  56.  
  57. Overridability: "new" is an operator that can be overridden by a class, while
  58. "malloc" is not overridable on a per-class basis.
  59.  
  60. ==============================================================================
  61.  
  62. Q36: Why doesn't C++ have a "realloc()" along with "new" and "delete"?
  63.  
  64. To save you from disaster.
  65.  
  66. When realloc() has to copy the allocation, it uses a BITWISE copy operation,
  67. which will tear most C++ objects to shreds.  C++ objects should be allowed to
  68. copy themselves: they use their own copy constructor or assignment operator.
  69.  
  70. ==============================================================================
  71.  
  72. Q37: How do I allocate / unallocate an array of things?
  73.  
  74. Use new[] and delete[]:
  75.  
  76.     Fred* p = new Fred[100];
  77.     //...
  78.     delete [] p;
  79.  
  80. Any time you use the "[...]" in the "new" expression, you *!*MUST*!* use "[]"
  81. in the "delete" statement.  This syntax is necessary because there is no
  82. syntactic difference between a pointer to a thing and a pointer to an array of
  83. things (something we inherited from C).
  84.  
  85. ==============================================================================
  86.  
  87. Q38: What if I forget the "[]" when "delete"ing array allocated via "new
  88.    Fred[n]"?
  89.  
  90. All life comes to a catastrophic end.
  91.  
  92. It is the programmer's --not the compiler's-- responsibility to get the
  93. connection between new[] and delete[] correct.  If you get it wrong, neither a
  94. compile-time nor a run-time error message will be generated by the compiler.
  95. Heap corruption is a likely result.  Or worse.  Your program will probably die.
  96.  
  97. ==============================================================================
  98.  
  99. Q39: Is it legal (and moral) for a member function to say "delete this"?
  100.  
  101. As long as you're careful, you'll be ok.
  102.  
  103. Here's how I define "careful":
  104. 1) You're absolutely 100% positive sure that "this" was allocated via "new"
  105.    (not by "new[]", nor by placement "new", by by plain ordinary "new").
  106. 2) You're absolutely 100% positive sure that your member function will be
  107.    the last member function invoked on this object.
  108. 3) After you do the suicide thing ("delete this;"), you must not touch any
  109.    piece of "this" object, including data or methods.
  110. 4) After you do the suicide thing ("delete this;"), you must not touch the
  111.    "this" pointer.  In other words, you must not examine it, compare it with
  112.    another pointer or with NULL, print it, cast it, do anything with it.
  113.  
  114. Naturally the usual caveats apply in cases where your "this" pointer is a
  115. pointer to a base class and the destructor isn't virtual.
  116.  
  117. ==============================================================================
  118.  
  119. Q40: How do I allocate multidimensional arrays using new?
  120.  
  121. There are many ways to do this, depending on how flexible you want the array
  122. sizing to be.  On one extreme, if you know all the dimensions at compile-time,
  123. you can allocate multidimensional arrays statically (as in C):
  124.  
  125.     class Fred { /*...*/ };
  126.  
  127.     void manipulateArray()
  128.     {
  129.       Fred matrix[10][20];
  130.  
  131.       //use matrix[i][j]...
  132.  
  133.       //no need for explicit deallocation
  134.     }
  135.  
  136. On the other extreme, if you want to allow the various slices of the matrix to
  137. have a different sizes, you can allocate everything off the freestore:
  138.  
  139.     void manipulateArray(unsigned nrows, unsigned ncols[])
  140.     //'nrows' is the number of rows in the array.
  141.     //therefore valid row numbers are from 0 to nrows-1 inclusive.
  142.     //'ncols[r]' is the number of columns in row 'r' ('r' in [0..nrows-1]).
  143.     {
  144.       Fred** matrix = new Fred*[nrows];
  145.       for (unsigned r = 0; r < nrows; ++r)
  146.         matrix[r] = new Fred[ ncols[r] ];
  147.  
  148.       //use matrix[i][j]...
  149.  
  150.       //deletion is the opposite of allocation:
  151.       for (r = nrows; r > 0; --r)
  152.         delete [] matrix[r-1];
  153.       delete [] matrix;
  154.     }
  155.  
  156. ==============================================================================
  157.  
  158. Q41: Does C++ have arrays whose length can be specified at run-time?
  159.  
  160. Yes, in the sense that STL has a vector template that provides this behavior.
  161. See on "STL" in the "Libraries" section.
  162.  
  163. No, in the sense that built-in array types need to have their length specified
  164. at compile time.
  165.  
  166. Yes, in the sense that even built-in array types can specify the first index
  167. bounds at run-time.  E.g., comparing with the previous FAQ, if you only need
  168. the first array dimension to vary, then you can just ask new for an array of
  169. arrays (rather than an array of pointers to arrays):
  170.  
  171.     const unsigned ncols = 100;
  172.     //'ncols' is not a run-time variable (number of columns in the array)
  173.  
  174.     class Fred { ... };
  175.  
  176.     void manipulateArray(unsigned nrows)
  177.     //'nrows' is a run-time variable (number of rows in the array)
  178.     {
  179.       Fred (*matrix)[ncols] = new Fred[nrows][ncols];
  180.  
  181.       //use matrix[i][j]
  182.  
  183.       //deletion is the opposite of allocation:
  184.       delete [] matrix;
  185.     }
  186.  
  187. You can't do this if you need anything other than the first dimension
  188. of the array to change at run-time.
  189.  
  190. ==============================================================================
  191.  
  192. Q42: How can I ensure objects of my class are always created via "new" rather
  193.    than as locals or global/static objects?
  194.  
  195. Make sure the class's constructors are "private:", and define "friend" or
  196. "static" fns that return a ptr to the objects created via "new" (make the
  197. constructors "protected:" if you want to allow derived classes).
  198.  
  199.     class Fred {    //only want to allow dynamicly allocated Fred's
  200.     public:
  201.       static Fred* create()                 { return new Fred();     }
  202.       static Fred* create(int i)            { return new Fred(i);    }
  203.       static Fred* create(const Fred& fred) { return new Fred(fred); }
  204.     private:
  205.       Fred();
  206.       Fred(int i);
  207.       Fred(const Fred& fred);
  208.       virtual ~Fred();
  209.     };
  210.  
  211.     main()
  212.     {
  213.       Fred* p = Fred::create(5);
  214.       ...
  215.       delete p;
  216.     }
  217.  
  218. ==============================================================================
  219. SECTION 10: Debugging and error handling
  220. ==============================================================================
  221.  
  222. Q43: How can I handle a constructor that fails?
  223.  
  224. Throw an exception.
  225.  
  226. Constructors don't have a return type, so it's not possible to use error codes.
  227. The best way to signal constructor failure is therefore to throw an exception.
  228.  
  229. Before C++ had exceptions, we signaled constructor failure by putting the
  230. object into a "half baked" state (e.g., by setting an internal status bit).
  231. There was a query ("inspector") method to check this bit, that allowed clients
  232. to discover whether they had a live object.  Other member functions would also
  233. check this bit, and, if the object wasn't really alive, do a no-op (or perhaps
  234. something more obnoxious such as "abort()").  This was really ugly.
  235.  
  236. ==============================================================================
  237.  
  238. Q44: How should I handle resources if my constructors may throw exceptions?
  239.  
  240. Every data member inside your object should clean up its own mess.
  241.  
  242. If a constructor throws an exception, the object's destructor is NOT run.  If
  243. your object has already done something that needs to be undone (such as
  244. allocating some memory, opening a file, or locking a semaphore), this "stuff
  245. that needs to be undone" MUST be remembered by a data member inside the object.
  246.  
  247. For example, rather than allocating memory into a raw "Fred*" data member, put
  248. the allocated memory into a "smart pointer" member object, and the destructor
  249. of this smart pointer will delete the Fred object when the smart pointer dies.
  250.  
  251. ==============================================================================
  252. SECTION 11: Const correctness
  253. ==============================================================================
  254.  
  255. Q45: What is "const correctness"?
  256.  
  257. A good thing.
  258.  
  259. Const correctness uses the keyword "const" to ensure const objects don't get
  260. mutated.  E.g., if function "f()" accepts a "String", and "f()" wants to
  261. promise not to change the "String", you:
  262.  
  263.  * can either pass by value:    void  f(      String  s   )  { /*...*/ }
  264.  * or by constant reference:    void  f(const String& s   )  { /*...*/ }
  265.  * or by constant pointer:    void  f(const String* sptr)  { /*...*/ }
  266.  * but NOT by non-const ref:    void  f(      String& s   )  { /*...*/ }
  267.  * NOR by non-const pointer:    void  f(      String* sptr)  { /*...*/ }
  268.  
  269. Attempted changes to "s" within a fn that takes a "const String&" are flagged
  270. as compile-time errors; neither run-time space nor speed is degraded.
  271.  
  272. Declaring the "constness" of a parameter is just another form of type safety.
  273. It is almost as if a constant String, for example, "lost" its various mutative
  274. operations.  If you find type safety helps you get systems correct (it does;
  275. especially in large systems), you'll find const correctness helps also.
  276.  
  277. ==============================================================================
  278.  
  279. Q46: Should I try to get things const correct "sooner" or "later"?
  280.  
  281. At the very, very, VERY beginning.
  282.  
  283. Back-patching const correctness results in a snowball effect: every "const" you
  284. add "over here" requires four more to be added "over there."
  285.  
  286. ==============================================================================
  287.  
  288. Q47: What is a "const member function"?
  289.  
  290. A member function that inspects (rather than mutates) its object.
  291.  
  292.     class Fred {
  293.     public:
  294.       void f() const;
  295.     };      // ^^^^^--- this implies "fred.f()" won't change "fred"
  296.  
  297. This means that the ABSTRACT (client-visible) state of the object isn't going
  298. to change (as opposed to promising that the "raw bits of the object's struct
  299. aren't going to change).  C++ compilers aren't allowed to take the "bitwise"
  300. interpretation, since a non-const alias could exist which could modify the
  301. state of the object (gluing a "const" ptr to an object doesn't promise the
  302. object won't change; it promises only that the object won't change VIA THAT
  303. POINTER).
  304.  
  305. "const" member functions are often called "inspectors."  Non-"const" member
  306. functions are often called "mutators."
  307.  
  308. ==============================================================================
  309.  
  310. Q48: What do I do if I want to update an "invisible" data member inside a
  311.    "const" member function?
  312.  
  313. Use "mutable", or use "const_cast".
  314.  
  315. A small percentage of inspectors need to make innocuous changes to data members
  316. (e.g., a "Set" object might want to cache its last lookup in hopes of improving
  317. the performance of its next lookup).  By saying the changes are "inocuous," I
  318. mean that the changes wouldn't be visible from outside the object's interface
  319. (otherwise the method would be a mutator rather than an inspector).
  320.  
  321. When this happens, the data member which will be modified should be marked as
  322. "mutable" (put the "mutable" keyword just before the data member's declaration;
  323. i.e., in the same place where you could put "const").  This tells the compiler
  324. that the data member is allowed to change during a const member function.  If
  325. you can't use "mutable", you can cast away the constness of "this" via
  326. "const_cast".  E.g., in "Set::lookup() const", you might say,
  327.  
  328.     Set* self = const_cast<Set*>(this);
  329.  
  330. After this line, "self" will have the same bits as "this" (e.g., "self==this"),
  331. but "self" is a "Set*" rather than a "const Set*".  Therefore you can use
  332. "self" to modify the object pointed to by "this".
  333.  
  334. ==============================================================================
  335.  
  336. Q49: Does "const_cast" mean lost optimization opportunities?
  337.  
  338. In theory, yes; in practice, no.
  339.  
  340. Even if a compiler outlawed "const_cast", the only way to avoid flushing the
  341. register cache across a "const" member function call would be to ensure that
  342. there are no non-const pointers that alias the object.  This can happen only in
  343. rare cases (when the object is constructed in the scope of the const member fn
  344. invocation, and when all the non-const member function invocations between the
  345. object's construction and the const member fn invocation are statically bound,
  346. and when every one of these invocations is also "inline"d, and when the
  347. constructor itself is "inline"d, and when any member fns the constructor calls
  348. are inline).
  349.  
  350. ==============================================================================
  351. SECTION 12: Inheritance
  352. ==============================================================================
  353.  
  354. Q50: Is inheritance important to C++?
  355.  
  356. Yep.
  357.  
  358. Inheritance is what separates abstract data type (ADT) programming from OOP.
  359.  
  360. ==============================================================================
  361.  
  362. Q51: When would I use inheritance?
  363.  
  364. As a specification device.
  365.  
  366. Human beings abstract things on two dimensions: part-of and kind-of.  A Ford
  367. Taurus is-a-kind-of-a Car, and a Ford Taurus has-a Engine, Tires, etc.  The
  368. part-of hierarchy has been a part of software since the ADT style became
  369. relevant; inheritance adds "the other" major dimension of decomposition.
  370.  
  371. ==============================================================================
  372.  
  373. Q52: How do you express inheritance in C++?
  374.  
  375. By the ": public" syntax:
  376.  
  377.     class Car : public Vehicle {
  378.             //^^^^^^^^---- ": public" is pronounced "is-a-kind-of-a'
  379.       //...
  380.     };
  381.  
  382. We state the above relationship in several ways:
  383.  * Car is "a kind of a" Vehicle
  384.  * Car is "derived from" Vehicle
  385.  * Car is "a specialized" Vehicle
  386.  * Car is the "subclass" of Vehicle
  387.  * Vehicle is the "base class" of Car
  388.  * Vehicle is the "superclass" of Car (this not as common in the C++ community)
  389.  
  390. ==============================================================================
  391.  
  392. Q53: Is it ok to convert a pointer from a derived class to its base class?
  393.  
  394. Yes.
  395.  
  396. A derived class is a specialized version of the base class ("Derived is a
  397. kind-of Base").  The upward conversion is perfectly safe, and happens all the
  398. time (if I am pointing at a car, I am in fact pointing at a vehicle):
  399.  
  400.     void f(Vehicle* v);
  401.     void g(Car* c) { f(c); }    //perfectly safe; no cast
  402.  
  403. Note that the answer to this FAQ assumes we're talking about "public"
  404. inheritance; see below on "private/protected" inheritance for "the other kind".
  405.  
  406. ==============================================================================
  407.  
  408. Q54: Derived* --> Base* works ok; why doesn't Derived** --> Base** work?
  409.  
  410. C++ allows a Derived* to be converted to a Base*, since a Derived object is a
  411. kind of a Base object.  However trying to convert a Derived** to a Base** is
  412. (correctly) flagged as an error (if it was allowed, the Base** could be
  413. dereferenced (yielding a Base*), and the Base* could be made to point to an
  414. object of a DIFFERENT derived class.  This would be an error.
  415.  
  416. As a corollary, an array of Deriveds is-NOT-a-kind-of array of Bases.  At
  417. Paradigm Shift, Inc. we use the following example in our C++ training sessions:
  418.  
  419.                "A bag of apples is NOT a bag of fruit".
  420.  
  421. If a bag of apples COULD be passed as a bag of fruit, someone could put a
  422. banana into the bag of apples!
  423.  
  424. ==============================================================================
  425.  
  426. Q55: Does array-of-Derived is-NOT-a-kind-of array-of-Base mean arrays are
  427.    bad?
  428.  
  429. Yes, "arrays are evil" (jest kidd'n :-).
  430.  
  431. There's a very subtle problem with using raw built-in arrays.  Consider this:
  432.  
  433.     void f(Base* arrayOfBase)
  434.     {
  435.       arrayOfBase[3].memberfn();
  436.     }
  437.  
  438.     main()
  439.     {
  440.       Derived arrayOfDerived[10];
  441.       f(arrayOfDerived);
  442.     }
  443.  
  444. The compiler thinks this is perfectly type-safe, since it can convert a
  445. Derived* to a Base*.  But in reality it is horrendously evil: since Derived
  446. might be larger than Base, the array index in f() not only isn't type safe, it
  447. may not even be pointing at a real object!  In general it'll be pointing
  448. somewhere into the innards of some poor Derived.
  449.  
  450. The root problem is that C++ can't distinguish between a ptr-to-a-thing and a
  451. ptr-to-an-array-of-things.  Naturally C++ "inherited" this feature from C.
  452.  
  453. NOTE: if we had used an array-like CLASS instead of using a raw array (e.g., an
  454. "Array<T>" rather than a "T[]"), this problem would have been properly trapped
  455. as an error at compile time rather than at run-time.
  456.  
  457. ==============================================================================
  458. SUBSECTION 12A: Inheritance -- Virtual functions
  459. ==============================================================================
  460.  
  461. Q56: What is a "virtual member function"?
  462.  
  463. A virtual function allows derived classes to replace the implementation
  464. provided by the base class.  The compiler ensures the replacement is always
  465. called whenever the object in question is actually of the derived class, even
  466. if the object is accessed by a base pointer rather than a derived pointer.
  467. This allows algorithms in the base class to be replaced in the derived class,
  468. even if users don't know about the derived class.
  469.  
  470. Note: the derived class can partially replace ("override") the base class
  471. method (the derived class method can invoke the base class version if desired).
  472.  
  473. ==============================================================================
  474.  
  475. Q57: How can C++ achieve dynamic binding yet also static typing?
  476.  
  477. In the following discussion, "ptr" means either a pointer or a reference.
  478.  
  479. When you have a ptr, there are two types: the (static) type of the ptr, and the
  480. (dynamic) type of the pointed-to object (the object may actually be of a class
  481. that is derived from the class of the ptr).
  482.  
  483. "Static typing" means that the "legality" of the call is checked based on the
  484. static type of the ptr: if the type of the ptr can handle the member fn,
  485. certainly the pointed-to object can handle it as well.
  486.  
  487. "Dynamic binding" means that the "code" that is called is based on the dynamic
  488. type of the pointed-to object.  This is called "dynamic binding," since the
  489. actual code being called is determined dynamically (at run time).
  490.  
  491. ==============================================================================
  492.  
  493. Q58: Should a derived class replace ("override") a non-virtual fn from a base
  494.    class?
  495.  
  496. It's legal, but it ain't moral.
  497.  
  498. Experienced C++ programmers will sometimes redefine a non-virtual fn for
  499. efficiency (the alternate implementation might make better use of the derived
  500. class' resources), or to get around the hiding rule (see below, and ARM
  501. ["Annotated Reference Manual"] sect.13.1).  However the client-visible effects
  502. must be IDENTICAL, since non-virtual fns are dispatched based on the static
  503. type of the ptr/ref rather than the dynamic type of the pointed-to/referenced
  504. object.
  505.  
  506. ==============================================================================
  507.  
  508. Q59: What's the meaning of, "Warning: Derived::f(int) hides Base::f(float)"?
  509.  
  510. It means you're going to die.
  511.  
  512. Here's the mess you're in: if Derived declares a member function named "f", and
  513. Base declares a member function named "f" with a different signature (e.g.,
  514. different parameter types and/or constness), then the Base "f" is "hidden"
  515. rather than "overloaded" or "overridden" (even if the Base "f" is virtual).
  516.  
  517. Here's how you get out of the mess: Derived must redefine the Base member
  518. function(s) that are hidden (even if they are non-virtual).  Normally this
  519. re-definition merely calls the appropriate Base member function.  E.g.,
  520.  
  521.     class Base {
  522.     public:
  523.       void f(int);
  524.     };
  525.  
  526.     class Derived : public Base {
  527.     public:
  528.       void f(double);
  529.       void f(int i) { Base::f(i); }
  530.     };             // ^^^^^^^^^^--- redefinition merely calls Base::f(int)
  531.  
  532. ==============================================================================
  533. SUBSECTION 12B: Inheritance -- Conformance
  534. ==============================================================================
  535.  
  536. Q60: Should I hide public member fns inherited from my base class?
  537.  
  538. Never, never, never do this.  Never.  NEVER!
  539.  
  540. Attempting to hide (eliminate, revoke) inherited public member functions is an
  541. all-too-common design error.  It usually stems from muddy thinking.
  542.  
  543. ==============================================================================
  544.  
  545. Q61: Is a "Circle" a kind-of an "Ellipse"?
  546.  
  547. Not if Ellipse promises to be able to change its size asymmetrically.
  548.  
  549. For example, suppose Ellipse has a "setSize(x,y)" method, and suppose this
  550. method promises "the Ellipse's width() will be x, and its height() will be y".
  551. In this case, Circle can't be a kind-of Ellipse.  Simply put, if Ellipse can do
  552. something Circle can't, then Circle can't be a kind of Ellipse.
  553.  
  554. This leaves two potential (valid) relationships between Circle and Ellipse:
  555.  * Make Circle and Ellipse completely unrelated classes.
  556.  * Derive Circle and Ellipse from a base class representing "Ellipses that
  557.    can't NECESSARILY perform an unequal-setSize operation."
  558.  
  559. In the first case, Ellipse could be derived from class "AsymmetricShape" (with
  560. setSize(x,y) being introduced in AsymmetricShape), and Circle could be derived
  561. from "SymmetricShape," which has a setSize(size) member fn.
  562.  
  563. In the second case, class "Oval" could only have "setSize(size)" which sets
  564. both the "width()" and the "height()" to "size", then derive both Ellipse and
  565. Circle from Oval.  Ellipse --but not Circle-- adds the "setSize(x,y)" operation
  566. (see the "hiding rule" for a caveat if the same method name "setSize()" is used
  567. for both operations).
  568.  
  569. ==============================================================================
  570.  
  571. Q62: Are there other options to the "Circle is/isnot kind-of Ellipse"
  572.    dilemma?
  573.  
  574. If you claim that all Ellipses can be squashed asymmetrically, and you claim
  575. that Circle is a kind-of Ellipse, and you claim that Circle can't be squashed
  576. asymmetrically, clearly you've got to adjust (revoke, actually) one of your
  577. claims.  Thus you've either got to get rid of "Ellipse::setSize(x,y)", get rid
  578. of the inheritance relationship between Circle and Ellipse, or admit that your
  579. "Circle"s aren't necessarily circular.
  580.  
  581. Here are the two most common traps new OO/C++ programmers regularly fall into.
  582. They attempt to use coding hacks to cover up a broken design (they redefine
  583. Circle::setSize(x,y) to throw an exception, call "abort()", or choose the
  584. average of the two parameters, or to be a no-op).  Unfortunately all these
  585. hacks will surprise users, since users are expecting "width() == x" and
  586. "height() == y".
  587.  
  588. The only rational way out of this would be to weaken the promise made by
  589. Ellipse's "setSize(x,y)" (e.g., you'd have to change it to, "This method MIGHT
  590. set width() to x and height() to y, or it might do NOTHING").  Unfortunately
  591. this dilutes the contract into dribble, since the user can't rely on any
  592. meaningful behavior.  The whole hierarchy therefore begins to be worthless
  593. (it's hard to convince someone to use an object if you have to shrug your
  594. shoulders when asked what the object does for them).
  595.  
  596. ==============================================================================
  597. SUBSECTION 12C: Inheritance -- Access rules
  598. ==============================================================================
  599.  
  600. Q63: Why can't my derived class access "private" things from my base class?
  601.  
  602. To protect you from future changes to the base class.
  603.  
  604. Derived classes do not get access to private members of a base class.  This
  605. effectively "seals off" the derived class from any changes made to the private
  606. members of the base class.
  607.  
  608. ==============================================================================
  609.  
  610. Q64: What's the difference between "public:", "private:", and "protected:"?
  611.  
  612. "Private:" is discussed in the previous section, and "public:" means "anyone
  613. can access it."  The third option, "protected:", makes a member (either data
  614. member or member fn) accessible to subclasses.
  615.  
  616. ==============================================================================
  617.  
  618. Q65: How can I protect subclasses from breaking when I change internal parts?
  619.  
  620. A class has two distinct interfaces for two distinct sets of clients:
  621.  * its "public:" interface serves unrelated classes.
  622.  * its "protected:" interface serves derived classes.
  623.  
  624. Unless you expect all your subclasses to be built by your own team, you should
  625. consider making your base class's bits be "private:", and use "protected:"
  626. inline access functions to access these data.  This way the private bits can
  627. change, but the derived class's code won't break unless you change the
  628. protected access functions.
  629.  
  630. ==============================================================================
  631. SUBSECTION 12D: Inheritance -- Constructors and destructors
  632. ==============================================================================
  633.  
  634. Q66: When my base class's constructor calls a virtual function, why doesn't my
  635.    derived class's override of that virtual function get invoked?
  636.  
  637. During the Base class's constructor, the object isn't yet a Derived, so if
  638. "Base::Base()" calls a virtual function "virt()", the "Base::virt()" will be
  639. invoked, even if "Derived::virt()" exists.
  640.  
  641. Similarly, during Base's destructor, the object is no longer a Derived, so when
  642. Base::~Base() calls "virt()", "Base::virt()" gets control, NOT the
  643. "Derived::virt()" override.
  644.  
  645. You'll quickly see the wisdom of this approach when you imagine the disaster if
  646. "Derived::virt()" touched a member object from the Derived class.
  647.  
  648. ==============================================================================
  649.  
  650. Q67: Does a derived class destructor need to explicitly call the base
  651.    destructor?
  652.  
  653. No, never explicitly call a destructor (where "never" means "rarely").
  654.  
  655. A derived class's destructor (whether or not you explicitly define one)
  656. AUTOMATICALLY invokes the destructors for member objects and base class
  657. subobjects.  Member objects are destroyed in the reverse order they appear
  658. within the class, then base class subobjects are destroyed in the reverse order
  659. that they appear in the class's list of base classes.
  660.  
  661. You should explicitly call a destructor ONLY in esoteric situations, such as
  662. when destroying an object created by the "placement new operator."
  663.  
  664. ==============================================================================
  665. SUBSECTION 12E: Inheritance -- Private and protected inheritance
  666. ==============================================================================
  667.  
  668. Q68: How do you express "private inheritance"?
  669.  
  670. When you use ": private" instead of ": public."  E.g.,
  671.  
  672.     class Foo : private Bar {
  673.       //...
  674.     };
  675.  
  676. ==============================================================================
  677.  
  678. Q69: How are "private inheritance" and "composition" similar?
  679.  
  680. Private inheritance is a syntactic variant of composition (has-a).
  681.  
  682. E.g., the "car has-a engine" relationship can be expressed using composition:
  683.  
  684.     class Engine {
  685.     public:
  686.       Engine(int numCylinders);
  687.       void start();            //starts this Engine
  688.     };
  689.  
  690.     class Car {
  691.     public:
  692.       Car() : e_(8) { }        //initializes this Car with 8 cylinders
  693.       void start() { e_.start(); }    //start this Car by starting its engine
  694.     private:
  695.       Engine e_;
  696.     };
  697.  
  698. The same "has-a" relationship can also be expressed using private inheritance:
  699.  
  700.     class Car : private Engine {
  701.     public:
  702.       Car() : Engine(8) { }        //initializes this Car with 8 cylinders
  703.       Engine::start;        //start this Car by starting its engine
  704.     };
  705.  
  706. There are several similarities between these two forms of composition:
  707.  * in both cases there is exactly one Engine member object contained in a Car.
  708.  * in neither case can users (outsiders) convert a Car* to an Engine*.
  709.  
  710. There are also several distinctions:
  711.  * the first form is needed if you want to contain several Engines per Car.
  712.  * the second form can introduce unnecessary multiple inheritance.
  713.  * the second form allows members of Car to convert a Car* to an Engine*.
  714.  * the second form allows access to the "protected" members of the base class.
  715.  * the second form allows Car to override Engine's virtual functions.
  716.  
  717. Note that private inheritance is usually used to gain access into the
  718. "protected:" members of the base class, but this is usually a short-term
  719. solution (translation: a band-aid; see below).
  720.  
  721. ==============================================================================
  722.  
  723. Q70: Which should I prefer: composition or private inheritance?
  724.  
  725. Composition.
  726.  
  727. Normally you don't WANT to have access to the internals of too many other
  728. classes, and private inheritance gives you some of this extra power (and
  729. responsibility).  But private inheritance isn't evil; it's just more expensive
  730. to maintain, since it increases the probability that someone will change
  731. something that will break your code.
  732.  
  733. A legitimate, long-term use for private inheritance is when you want to build a
  734. class Fred that uses code in a class Wilma, and the code from class Wilma needs
  735. to invoke methods from your new class, Fred.  In this case, Fred calls
  736. non-virtuals in Wilma, and Wilma calls (usually pure) virtuals in itself, which
  737. are overridden by Fred.  This would be much harder to do with composition.
  738.  
  739.     class Wilma {
  740.     protected:
  741.       void fredCallsWilma()
  742.         { cout << "Wilma::fredCallsWilma()\n"; wilmaCallsFred(); }
  743.       virtual void wilmaCallsFred() = 0;
  744.     };
  745.  
  746.     class Fred : private Wilma {
  747.     public:
  748.       void barney()
  749.         { cout << "Fred::barney()\n"; Wilma::fredCallsWilma(); }
  750.     protected:
  751.       virtual void wilmaCallsFred()
  752.         { cout << "Fred::wilmaCallsFred()\n"; }
  753.     };
  754.  
  755. ==============================================================================
  756.  
  757. Q71: Should I pointer-cast from a "privately" derived class to its base
  758.    class?
  759.  
  760. Generally, No.
  761.  
  762. From a method or friend of a privately derived class, the relationship to the
  763. base class is known, and the upward conversion from PrivatelyDer* to Base* (or
  764. PrivatelyDer& to Base&) is safe; no cast is needed or recommended.
  765.  
  766. However users of PrivateDer should avoid this unsafe conversion, since it is
  767. based on a "private" decision of PrivateDer, and is subject to change without
  768. notice.
  769.  
  770. ==============================================================================
  771.  
  772. Q72: How is protected inheritance related to private inheritance?
  773.  
  774. Similarities: both allow overriding virtuals in the private/protected base
  775. class, neither claims the derived is a kind-of its base.
  776.  
  777. Dissimilarities: protected inheritance allows derived classes of derived
  778. classes to know about the inheritance relationship (it exposes your grand kids
  779. to your implementation details).  This has both benefits (it allows subclasses
  780. of the protected derived class to exploit the relationship to the protected
  781. base class) and costs (the protected derived class can't change the
  782. relationship without potentially breaking further derived classes).
  783.  
  784. Protected inheritance uses the ": protected" syntax:
  785.  
  786.     class Car : protected Engine {
  787.       //...
  788.     };
  789.  
  790. ==============================================================================
  791.  
  792. Q73: What are the access rules with "private" and "protected" inheritance?
  793.  
  794. Take these classes as examples:
  795.  
  796.     class B                    { /*...*/ };
  797.     class D_priv : private   B { /*...*/ };
  798.     class D_prot : protected B { /*...*/ };
  799.     class D_publ : public    B { /*...*/ };
  800.     class UserClass            { B b; /*...*/ };
  801.  
  802. None of the subclasses can access anything that is private in B.  In D_priv,
  803. the public and protected parts of B are "private".  In D_prot, the public and
  804. protected parts of B are "protected".  In D_publ, the public parts of B are
  805. public and the protected parts of B are protected (D_publ is-a-kind-of-a B).
  806. Class "UserClass" can access only the public parts of B, which "seals off"
  807. UserClass from B.
  808.  
  809. To make a public member of B so it is public in D_priv or D_prot, state the
  810. name of the member with a "B::" prefix.  E.g., to make member "B::f(int,float)"
  811. public in D_prot, you would say:
  812.  
  813.     class D_prot : protected B {
  814.     public:
  815.       B::f;    //note: not  "B::f(int,float)"
  816.     };
  817.  
  818. ==============================================================================
  819. SECTION 13: Abstraction
  820. ==============================================================================
  821.  
  822. Q74: What's the big deal of separating interface from implementation?
  823.  
  824. Interfaces are a company's most valuable resources.  Designing an interface
  825. takes longer than whipping together a concrete class which fulfills that
  826. interface.  Furthermore interfaces require the time of more expensive people.
  827.  
  828. Since interfaces are so valuable, they should be protected from being tarnished
  829. by data structures and other implementation artifacts.  Thus you should
  830. separate interface from implementation.
  831.  
  832. ==============================================================================
  833.  
  834. Q75: How do I separate interface from implementation in C++ (like Modula-2)?
  835.  
  836. Use an ABC (see next FAQ).
  837.  
  838. ==============================================================================
  839.  
  840. Q76: What is an ABC ("abstract base class")?
  841.  
  842. At the design level, an ABC corresponds to an abstract concept.  If you asked a
  843. Mechanic if he repaired Vehicles, he'd probably wonder what KIND-OF Vehicle you
  844. had in mind.  Chances are he doesn't repair space shuttles, ocean liners,
  845. bicycles, or nuclear submarines.  The problem is that the term "Vehicle" is an
  846. abstract concept (e.g., you can't build a "vehicle" unless you know what kind
  847. of vehicle to build).  In C++, class Vehicle would be an ABC, with Bicycle,
  848. SpaceShuttle, etc, being subclasses (an OceanLiner is-a-kind-of-a Vehicle).  In
  849. real-world OOP, ABCs show up all over the place.
  850.  
  851. As programming language level, an ABC is a class that has one or more pure
  852. virtual member functions (see next FAQ).  You cannot make an object (instance)
  853. of an ABC.
  854.  
  855. ==============================================================================
  856.  
  857. Q77: What is a "pure virtual" member function?
  858.  
  859. A member function of an ABC that you can implement only in a derived class.
  860.  
  861. Some member functions exist in concept, but can't have any actual defn.  E.g.,
  862. suppose I asked you to draw a Shape at location (x,y) that has size 7.  You'd
  863. ask me "what kind of shape should I draw?" (circles, squares, hexagons, etc,
  864. are drawn differently).  In C++, we indicate the existence of the "draw()"
  865. method, but we recognize it can (logically) be defined only in subclasses:
  866.  
  867.     class Shape {
  868.     public:
  869.       virtual void draw() const = 0;
  870.       //...                     ^^^--- "= 0" means it is "pure virtual"
  871.     };
  872.  
  873. This pure virtual function makes "Shape" an ABC.  If you want, you can think of
  874. the "= 0" syntax as if the code were at the NULL pointer.  Thus "Shape"
  875. promises a service to its users, yet Shape isn't able to provide any code to
  876. fulfill that promise.  This ensures any actual object created from a [concrete]
  877. class derived of Shape *WILL* have the indicated member fn, even though the
  878. base class doesn't have enough information to actually DEFINE it yet.
  879.  
  880. ==============================================================================
  881.  
  882. Q78: How can I provide printing for an entire hierarchy of classes?
  883.  
  884. Provide a friend operator<< that calls a protected virtual function:
  885.  
  886.     class Base {
  887.     public:
  888.       friend ostream& operator<< (ostream& o, const Base& b)
  889.         { b.print(o); return o; }
  890.       //...
  891.     protected:
  892.       virtual void print(ostream& o) const;  //or "=0;" if "Base" is an ABC
  893.     };
  894.  
  895.     class Derived : public Base {
  896.     protected:
  897.       virtual void print(ostream& o) const;
  898.     };
  899.  
  900. Now all subclasses of Base merely provide their own "print(ostream&) const"
  901. member function (they all share the common "<<" operator).  This technique
  902. allows friends to ACT as if they supported dynamic binding.
  903.  
  904. ==============================================================================
  905.  
  906. Q79: When should my destructor be virtual?
  907.  
  908. When you may "delete" a derived object via a base pointer.
  909.  
  910. Virtual fns bind to the code associated with the class of the object, rather
  911. than with the class of the pointer/ref.  When you say "delete basePtr", and the
  912. base class has a virtual destructor, the destructor that gets invoked is the
  913. one associated with the type of the object *basePtr, rather than the one
  914. associated with the type of the pointer.  This is generally A Good Thing.
  915.  
  916. To make life easy for you, the only time you wouldn't want to make a class's
  917. destructor virtual is if that class has NO virtual fns, since the introduction
  918. of the first virtual fn imposes some space overhead in each object (typically
  919. one machine word).  This is how the compiler implements the magic of dynamic
  920. binding; it usually boils down to an extra ptr per object called the "virtual
  921. table pointer" or "vptr".
  922.  
  923. ==============================================================================
  924.  
  925. Q80: What is a "virtual constructor"?
  926.  
  927. An idiom that allows you to do something that C++ doesn't directly support.
  928.  
  929. You can get the effect of virtual constructor by a virtual "createCopy()"
  930. member fn (for copy constructing), or a virtual "createSimilar()" member fn
  931. (for the default constructor).
  932.  
  933.     class Shape {
  934.     public:
  935.       virtual ~Shape() { }        //see on "virtual destructors" for more
  936.       virtual void draw() = 0;
  937.       virtual void move() = 0;
  938.       //...
  939.       virtual Shape* createCopy() const = 0;
  940.       virtual Shape* createSimilar() const = 0;
  941.     };
  942.  
  943.     class Circle : public Shape {
  944.     public:
  945.       Circle* createCopy()    const { return new Circle(*this); }
  946.       Circle* createSimilar() const { return new Circle(); }
  947.       //...
  948.     };
  949.  
  950. The invocation of "Circle(*this)" is that of copy construction ("*this" has
  951. type "const Circle&" in these methods).  "createSimilar()" is similar, but it
  952. constructs a "default" Circle.
  953.  
  954. Users use these as if they were "virtual constructors":
  955.  
  956.     void userCode(Shape& s)
  957.     {
  958.       Shape* s2 = s.createCopy();
  959.       Shape* s3 = s.createSimilar();
  960.       //...
  961.       delete s2;    //relies on destructor being virtual!!
  962.       delete s3;    // ditto
  963.     }
  964.  
  965. This fn will work correctly regardless of whether the Shape is a Circle,
  966. Square, or some other kind-of Shape that doesn't even exist yet.
  967.  
  968. --
  969. Paradigm Shift, Inc. / P.O. Box 5108 / Potsdam, NY  13676
  970. Technology consulting services
  971. cline@parashift.com / Voice: 315-353-6100 / FAX: 315-353-6110
  972.